package com.linchong.concurrency.chapter9;

import lombok.Synchronized;

import java.util.stream.Stream;

/**
 * @Author:linchong
 * @CreateTime:2020-07-28 08:23
 * @Description:多生产-消费者实例 需求：10个线程去生产和消费
 */
public class MutiProduceConsumerDemo {

	private final static Object LOCK = new Object();

	private volatile boolean isProduce = false;

	private int i = 0;

	private void produce() {
		synchronized (LOCK) {
			while (isProduce) {
				try {
					LOCK.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			i++;
			System.out.println("生产者生产:" + i);
			isProduce = true;
			LOCK.notifyAll();
		}
	}


	private void cosume() {
		synchronized (LOCK) {
			while (isProduce) {
				System.out.println("消费者消费：" + i);
				isProduce = false;
				LOCK.notifyAll();
			}
			try {
				LOCK.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		MutiProduceConsumerDemo muti = new MutiProduceConsumerDemo();
		Stream.of("Produce-1","Produce-2","Produce-3").forEach(p->{
			new Thread(p){
				@Override
				public void run() {
					while (true){
						muti.produce();
						try {
							Thread.sleep(10);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}.start();
		});

		Stream.of("Consume-1","Consume-2").forEach(c->{
			new Thread(c){
				@Override
				public void run() {
					while (true){
						muti.cosume();
						try {
							Thread.sleep(10);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}.start();
		});
	}
}
